﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Extensions.cs" company="Matthias Friedrich">
//   Copyright © Matthias Friedrich 2013
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

namespace CommandlineHandling
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Reflection;

    internal static class Extensions
    {
        public static T Convert<T>(this string s)
        {
            TypeConverter converter = TypeDescriptor.GetConverter(typeof(T));
            if (converter.CanConvertFrom(typeof(string)))
            {
                return (T)converter.ConvertFrom(s);
            }

            return default(T);
        }

        public static IEnumerable<TAttribute> ReflectAttribute<TAttribute>(this Type t, bool inherit) where TAttribute : Attribute
        {
            ExceptionExtensions.ThrowArgumentNullException(t, () => t);

            object[] attributes;
            if ((attributes = t.GetCustomAttributes(typeof(TAttribute), inherit)) != null)
            {
                foreach (object next in attributes)
                {
                    yield return (TAttribute)next;
                }
            }
        }

        public static IEnumerable<TAttribute> ReflectAttributes<TAttribute>(this MemberInfo member, bool inherit) where TAttribute : Attribute
        {
            ExceptionExtensions.ThrowArgumentNullException(member, () => member);

            object[] attributes;
            if ((attributes = member.GetCustomAttributes(typeof(TAttribute), inherit)) != null)
            {
                foreach (object next in attributes)
                {
                    yield return (TAttribute)next;
                }
            }
        }
    }
}